package com.shizhefei.view.largeimage.remote;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;


public class EventReceiver {
    private EventReceiver() {
        Log.d("wangweili:", "create instance");
        running = false;
    }
    private final static int PORT = 8899;
    volatile boolean running = false;
    static EventReceiver receiver = null;

    ServerSocket serverSocket = null;
    Socket socket = null;

    public IReceiveMonitor getReceive_monitor() {
        return receive_monitor;
    }

    public void setReceive_monitor(IReceiveMonitor receive_monitor) {
        this.receive_monitor = receive_monitor;
    }

    IReceiveMonitor receive_monitor = null;

    public static EventReceiver getInstance() {
        if (receiver == null) {
            receiver = new EventReceiver();
        }
        return receiver;
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

    public void stopReceiver() {
        if (!running) {
            return;
        }
        running = false;
        try {
            Log.d("wangweili:", "close server socket !!!");
            if (serverSocket != null) {
                serverSocket.close();
                serverSocket = null;
            }
            if (socket != null) {
                Log.d("wangweili:", "close client socket !!!");
                socket.close();
                socket = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void startReceiver() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Log.d("wangweili:", "receiver want to run !!!");
                running = true;
                while (running) {
                    try {
                        Log.d("wangweili:", "receiver started");
                        serverSocket = new ServerSocket(PORT);
                        socket = serverSocket.accept();
                        Log.d("wangweili:", "receiver accept: " + socket.toString().trim());
                        OutputStream os = socket.getOutputStream();
                        InputStream is = socket.getInputStream();
                        byte[] buffer = new byte[256];
                        boolean reading = true;
                        while (reading) {
                            Log.d("wangweili:", "receiver reading ........................");
                            int cnt_read = 0;
                            int len_read = 256;
                            while (cnt_read != 256) {
                                int r = 0;
                                try {
                                    r = is.read(buffer, cnt_read, len_read);
                                    cnt_read += r;
                                    len_read -= r;
                                    Log.d("wangweili:", " read " + r + "bytes");
                                    if (r == -1) {
                                        reading = false;
                                        socket.close();
                                        socket = null;
                                        serverSocket.close();
                                        serverSocket = null;
                                        break;
                                    }
                                    String request = new String(buffer, 0, 256, Charset.defaultCharset());
                                    try {
                                        JSONObject jobj = new JSONObject(request.trim());
                                        if (receive_monitor != null) {
                                            receive_monitor.onEventReceive(jobj);
                                        }
                                    } catch (JSONException e) {
                                        // throw new RuntimeException(e);
                                        e.printStackTrace();
                                    }
                                    Log.d("wangweili:", "message has receiver" + request.trim());
                                    StringBuilder sb = new StringBuilder();
                                    sb.append("message has receiver").setLength(64);
                                    os.write(sb.toString().getBytes());
                                } catch (IOException e) {
                                    reading = false;
                                    if (serverSocket != null) {
                                        serverSocket.close();
                                        serverSocket = null;
                                    }
                                    if (socket != null) {
                                        Log.d("wangweili:", "close client socket !!!");
                                        socket.close();
                                        socket = null;
                                    }
                                    break;
                                }
                            }
                        }

//                        if (serverSocket != null) {
//                            serverSocket.close();
//                            serverSocket = null;
//                        }
//                        if (socket != null) {
//                            Log.d("wangweili:", "close client socket !!!");
//                            socket.close();
//                            socket = null;
//                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        running = false;
                        Log.d("wangweili:", "receiver want stop !!!");
                    }
                }
            }
        };
        new Thread(runnable).start();
    }
}
